<template>
  <page-view class="shop-cart">
    <page-header title="购物车" :show-back="true"></page-header>
    <div class="content-box">
      <tabs v-model:active="tabIndex" animated>
        <tab title="购物车列表"
          ><list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <swipe-cell v-for="item in shopCartList" :key="item.id">
              <card
                :price="item.foodInfo.price"
                :title="item.foodInfo.food_name"
                :thumb="BaseURL + item.foodInfo.food_img"
              >
                <template #tags>
                  <stepper
                    v-model="item.count"
                    theme="round"
                    button-size="19"
                    disable-input
                    disable-minus
                    @plus="foodCountPlus(item.fid)"
                  />
                </template>
              </card>

              <template #right>
                <Button
                  square
                  text="删除"
                  type="danger"
                  class="delete-button"
                  @click="deleteMyShopCartFoodById(item.id)"
                />
              </template>
            </swipe-cell>
          </list>
        </tab>
        <tab title="收货地址">
          <address-list
            v-model="w"
            :list="addressList"
            default-tag-text="默认"
            @add="onAdd"
            @edit="onEdit"
          />
        </tab>
      </tabs>
    </div>
    <submit-bar
      :price="allMoney"
      button-text="提交订单"
      @submit="submitOrder"
    />
  </page-view>
</template>

<script>
import {
  Tab,
  Tabs,
  List,
  SwipeCell,
  Card,
  Stepper,
  Button,
  Dialog,
  SubmitBar,
  AddressList,
  Toast,
} from "vant";
import { onMounted, reactive, toRefs, computed, ref } from "vue";
import PageView from "@/components/PageView.vue";
import api from "@/utils/api";
import { useRoute, useRouter } from "vue-router";
export default {
  components: {
    PageView,
    Tab,
    Tabs,
    List,
    SwipeCell,
    Dialog,
    Card,
    Stepper,
    Button,
    SubmitBar,
    AddressList,
  },

  setup() {
    let info = reactive({
      tabIndex: 1,
      shopCartList: [],
      loading: false,
      finished: false,
      pageCount: 0,
      pageEnd: 0,
      pageIndex: 1,
      pageStart: 1,
      totalCount: 0,
      allMoney: 0,
      //地址列表
      w: 225,
      //地址列表
      addressList: [],
    });
    //默认中的
    let route = useRoute();
    let router = useRouter();
    // 获取购物车列表
    const foodCountPlus = async (fid) => {
      await api.shopCart.addToShopCart({
        // 商品的fid
        fid: fid,
        // 数量
        count: 1,
      });
    };

    //删除商品
    const deleteMyShopCartFoodById = (id) => {
      Dialog.confirm({
        title: "删除",
        message: "如果删除了就找不到了",
      })
        .then(async () => {
          // 发起删除操作
          await api.shopCart.deleteMyShopCartFoodById(id);
          let index = info.shopCartList.findIndex((item) => item.id === id);
          if (index != -1) {
            info.shopCartList.splice(index, 1);
          }
          // 删除成功后重新获取购物车列表
        })
        .catch(() => {
          // 取消删除
        });
    };

    //获取数据
    const onLoad = async () => {
      info.loading = true;
      info.finished = false;
      if (info.pageIndex < info.pageCount) {
        // 如果当前页码小于请求回来的最大页码,将当前页码加1并再次发起请求
        getShopCartList(Number(info.pageIndex) + 1);
      }
    };

    //通过页数找商品(将起始页,总页数,当前页分别赋值)
    const getShopCartList = async (pageIndex = 1) => {
      info.loading = true;
      info.finished = false;
      let res = await api.shopCart.getListByPage(pageIndex);
      info.pageIndex = +res.pageIndex;
      info.pageEnd = res.pageEnd;
      info.pageStart = res.pageStart;
      info.pageCount = res.pageCount;
      info.totalCount = res.totalCount;
      info.shopCartList.push(...res.listData);
      info.loading = false;
      info.finished = info.pageIndex >= info.pageCount;
    };
    //异步提交
    const submitOrder = async () => {
      if (info.w != 0) {
        if (info.addressList.length > 0) {
          let qig = {
            aid: info.w,
            foodList: [],
          };
          info.shopCartList.forEach((item) => {
            qig.foodList.push({
              fid: item.fid,
              count: item.count,
            });
          });
          console.log(qig);
          try {
            let res = await api.order.submitOrder(qig);
            Dialog.alert({
              title: "给钱，西内！",
              message: "提交成功",
            }).then(() => {
              router.push({
                name: "order",
              });
            });
            // router.push({ name: "order" });
          } catch (e) {
            console.log(e);
          }
        } else {
          Toast("请选择收货地址");
          return;
        }
      } else {
        Toast.fail("请选择地址");
        return;
      }
    };
    //获取总价
    const allMoney = computed(() => {
      let money = 0;
      info.shopCartList.forEach((item) => {
        money += item.foodInfo.price * item.count.toFixed(2);
      });
      // 分数形式所以乘以100
      return money * 100;
    });

    //地址
    // 地址添加
    const onAdd = () => {
      router.push({ name: "AddressInfo" });
      Toast("新增地址");
    };
    //获取自己的地址列表
    const getAddressList = async () => {
      let res = await api.addressInfo.getAddressInfoList();
      info.w = res[0].id;
      //拿到自己的地址列表res(信息对不上键名不对)
      info.addressList = res.map((item) => {
        return {
          id: item.id,
          name: item.person_name,
          tel: item.phone,
          address: item.address,
          tag: item.tag,
        };
      });
    };
    // 地址编辑
    const onEdit = (item, index) => {
      // item拿到的是当前地址的id，address，name，tel
      router.push({ name: "EditAddressInfo", query: { id: item.id } });
    };

    onMounted(() => {
      getShopCartList();
      getAddressList();
    });
    return {
      ...toRefs(info),
      foodCountPlus,
      deleteMyShopCartFoodById,
      onLoad,
      submitOrder,
      allMoney,
      onEdit,
      onAdd,
    };
  },
};
</script>

<style lang="scss" scoped>
.delete-button {
  height: 100%;
}
// 深度选择器（不知道什么东西）
::v-deep .van-card_content > div:first-child {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}
::v-deep .van-address-list__bottom {
  position: unset;
}
</style>
